//
//  PatronDetailViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 2/28/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "PatronDetailViewController.h"
#import "EditPatronDetailViewController.h"
#import "Patron.h"
#import "CheckoutRecordViewController.h"
#import "CheckoutHistoryNavigationViewController.h"
#import "ChargeHistoryNavigationViewController.h"

@interface PatronDetailViewController ()

@end

@implementation PatronDetailViewController
@synthesize delegate;

- (void)setDetailItem:(id)newDetailItem
{
    // allow editing since we now have a detail item
    [self.navigationItem.rightBarButtonItem setEnabled:YES];
    
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        
        NSLog(@"setDetailItem: Configuring DVC for Patron with last name %@",[_detailItem lastName]);
        
        // update title
        NSMutableString *title = [[NSMutableString alloc] init];
        [title appendString:[_detailItem lastName]];
        [title appendString:@", "];
        [title appendString:[_detailItem firstName]];
        [self setTitle:title];
        
        // Update the view.
        [self.tableView reloadData];
    }
}

- (IBAction)editModeButton:(id)sender {
    
    [self performSegueWithIdentifier:@"EditPatron" sender:_detailItem];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqual: @"EditPatron"]) {
        EditPatronDetailViewController *nextController = segue.destinationViewController;
        nextController.thePatron = sender;
        [nextController setDelegate:self];
    } else if ([[segue identifier] isEqual: @"CheckoutHistory"]) {
        CheckoutHistoryNavigationViewController *nextController = segue.destinationViewController;
        [nextController setPassThroughPatron:sender];
        [nextController setDelegate:self];
    } else if ([[segue identifier] isEqual: @"CheckoutDetail"]) {
        CheckoutHistoryNavigationViewController *nextController = segue.destinationViewController;
        [nextController setPassThroughRecord:sender];
        [nextController setDelegate:self];
    } else if ([[segue identifier] isEqual: @"AccountHistory"]) {
        ChargeHistoryNavigationViewController *nextController = segue.destinationViewController;
        [nextController setPassThroughPatron:sender];
        [nextController setDelegate:self];
        
    }
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // disallow editing since we have no detail item at first
    [self.navigationItem.rightBarButtonItem setEnabled:NO];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // no patron selected
    if (!_detailItem) {
        return 1;
    }
    
    // patron info, checkout info, account info
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    
    // no patron selected
    if (!_detailItem) {
        return 1;
    }
    
    switch (section) {
        case 0:
            // last name, first name, email, type, phone, status
            rows = 6;
            break;
        case 1:
            // # of checked out items + 1 for history
            rows = [[_detailItem checkoutsActive] count] + 1;
            break;
        case 2:
            // 1 row for account history button
            rows = 1;
            break;
        default:
            break;
    }
    
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText;
    NSString *cellDetailText;
    NSString *CellIdentifier = @"patronDetailCell"; // standard type of cell to use
    
    // depends on the section #
    switch (indexPath.section) {
        case 0:
            // patron info section - depends on row
            switch (indexPath.row) {
                case 0:
                    cellText = @"Last Name";
                    cellDetailText = [_detailItem lastName];
                    break;
                case 1:
                    cellText = @"First Name";
                    cellDetailText = [_detailItem firstName];
                    break;
                case 2:
                    cellText = @"Email";
                    cellDetailText = [_detailItem email];
                    break;
                case 3:
                    cellText = @"Type";
                    cellDetailText = [_detailItem patronType];
                    break;
                case 4:
                    cellText = @"Phone";
                    cellDetailText = [_detailItem telephone];
                    break;
                case 5:
                    cellText = @"Status";
                    if ([_detailItem active]) {
                        cellDetailText = @"Active";

                    } else {
                        cellDetailText = @"Inactive";
                    }
                    break;
            }
            break;
        case 1:
            // checkouts section
            if (indexPath.row == [[_detailItem checkoutsActive] count]) {
                // this is the "View Checkout History" row
                CellIdentifier = @"patronDetailCellBasicWithDisclosure";
                cellText = @"View Checkout History";
                
            } else {
                // this is a row for an active checkout
                CellIdentifier = @"patronDetailCellRightDetail";
                cellText = [[[_detailItem checkoutsActive] objectAtIndex:indexPath.row] itemType];
                
                NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
                [dateFormat setDateFormat:@"MM/dd/yyyy"];
                
                cellDetailText = [NSString stringWithFormat:@"Due: %@",[dateFormat stringFromDate:[[[_detailItem checkoutsActive] objectAtIndex:indexPath.row] dueDate]]];

            }
            break;
        case 2:
            // account history section
            CellIdentifier = @"patronDetailCellBasicWithDisclosure";
            cellText = @"View Account History";
            break;
        default:
            break;
    }
    
    UITableViewCell *cell;
    
    // no patron selected
    if (!_detailItem) {
        CellIdentifier = @"patronCellBasic";
        
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        
        cell.textLabel.text = @"No patron selected";
        //cell.accessoryType = UITableViewCellAccessoryNone;
        //cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.textLabel.text = cellText;
    cell.detailTextLabel.text = cellDetailText;
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *title = nil;
    
    if (!_detailItem) {
        return title;
    }
    
    // depends on section
    switch (section) {
        // patron info
        case 0:
            title = @"Patron Information";
            break;
        case 1:
            title = @"Checked Out Items";
            break;
        case 2:
            title = @"Account Information";
            break;
    }
    
    return title;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        // checkout information
        if (indexPath.row == [[_detailItem checkoutsActive] count]) {
            // go to checkout history
            [self performSegueWithIdentifier:@"CheckoutHistory" sender:_detailItem];
            
        } else {
            // go to checkout detail pop up for selected entry
            [self performSegueWithIdentifier:@"CheckoutDetail" sender:[[_detailItem checkoutsActive] objectAtIndex:indexPath.row]];
        }
    } else if (indexPath.section == 2) {
        // account information
        NSLog(@"didSelect AccountHistory row");
        [self performSegueWithIdentifier:@"AccountHistory" sender:_detailItem];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
